var oneReview = '<div class="oneReview"><div class="revTop"></div><div class="revContent"><div class="revRating">Értékelés<span>{rating}</span></div><span class="revOwner">{revOwner}</span>{review}<span class="revTime">{revTime}</span></div><div class="revBottom"></div></div>';
var reviewsList = $empty();
var reviewPreview = $empty();
var revPagination = $empty();

var buildRevPagination = new Class({
	Implements: [Options],
	options: {
		container: reviewsList,
		oneReview: oneReview,
		page: 1, 
		showNumbers: 3
	},
	pages : 0,
	initialize: function(episodeId, options){
		this.setOptions(options);
		this.episodeId = episodeId;
		this.page = this.options.page;
		
		this.loadContent();
	},
	loadContent : function(){
		new Request.JSON({url: api + 'getreviews.json|' + this.episodeId + '|' + this.page,
			onSuccess: function(json) {
				if(json){
					this.pages = (json.pages) ? json.pages : 1;
					this.setFlow(json.reviews);
				}
				this.setPagination();
			}.bind(this)
		}).send();
	},
	setPagination: function(){
		var addNumber = function(i, pagin, text){
			text = (text) ? text : i;
			var a = new Element('a',{'html': text})
			.inject(pagin);
			if(i != false){
				a.setProperty('rel', i)
			}
			else {
				a.addClass('inactive');
			}
			if(i == on_page && text == i){
				a.addClass('selected');
			}
			else if(text != i){
				a.addClass('noborder');
			}
		};
		
		var pages = this.pages;

		if(pages < 2)
		{
			if(this.paginationBottom)
				this.paginationBottom.dispose();
			if(this.paginationTop)
				this.paginationTop.dispose();
			return false;
		}
		this.pagination = new Element('div', {'class' : 'revPagination'});
		
		var show = this.options.showNumbers; 
		var on_page = this.page;
		
		addNumber((on_page != 1) ? (on_page.toInt() - 1) : false, this.pagination, '<big>&lsaquo;</big> Előző');
					
		addNumber(1,this.pagination);
								
		if(pages > show){
			var start_cnt = Math.min(Math.max(1, (on_page-(show-1))), pages - show);
			var end_cnt =  Math.max( Math.min(pages, on_page + (show - 1)), show+1);				
			
			if(start_cnt > 1)
				new Element('span', {'text' : '...'}).inject(this.pagination);
				
			for(var i = start_cnt + 1; i < end_cnt; i++){
				addNumber(i,this.pagination);
			}	
			
			if(end_cnt < pages)
				new Element('span', {'text' : '...'}).inject(this.pagination);
		} 
		else {
			for(var i = 2; i < pages; i++){
				addNumber(i,this.pagination);
			}
		}
		
		addNumber(pages,this.pagination);
		
		addNumber((on_page != pages) ? (on_page.toInt() + 1) : false,this.pagination, 'Következő <big>&rsaquo;</big>');
		
		if(this.paginationBottom && this.paginationTop){
			var bottom = this.pagination.clone();
			bottom.replaces(this.paginationBottom);
			var top = this.pagination.clone();
			top.replaces(this.paginationTop);
			this.paginationBottom = bottom;
			this.paginationTop = top;
		}
		else {
			this.paginationBottom = this.pagination.clone();
			this.paginationBottom.inject(this.options.container, 'after');
			this.paginationTop = this.pagination.clone();
			this.paginationTop.inject(this.options.container, 'before');
		}
		var pagi = this;
		$$(this.paginationTop.getChildren('a'), this.paginationBottom.getChildren('a')).
			addEvent('click', function(e){
				e.preventDefault();
				var pag = this.get('rel');
				if(!pag)
					return false;
				pagi.page = pag;
				pagi.setPagination();
				pagi.loadContent();
				window.scrollTo(window.getScroll().x, pagi.options.container.getPosition().y-30);
			});
	},
	setFlow: function(reviews){
		if($type(reviews) != 'array')
			return false;
		var html = '';
		reviews.each(function(item){

			item.revOwner = (item.user_settings.fb && item.user_settings.fb.username) ? item.user_settings.fb.username : (item.user_settings.fb && item.user_settings.fb.first_name) ? ('{last_name} {first_name}').substitute(item.user_settings.fb) : item.revOwner.split("@",1);
			
			item.revTime = new Date().parse(item.revTime).timeDiffInWords();
			item.review = item.review.replace(/\n/g,'<br />').trim();
			
			var oneReview = this.options.oneReview;
			oneReview = oneReview.substitute(item);
			html += oneReview;
		}.bind(this));
		var temp = new Element('div', {'html' : html});
		
		this.options.container.set('html',html);
	}
});

var makeReviewPreview = new Class({
	one : $empty(),
	revcont : $empty(),
	timecont : $empty(),
	startTime: $empty(),
	textcontainer: $('review'),
	wordCount: $('wordCount'),
	initialize: function(){
		this.textcontainer.addEvents({
			keyup: this.fillReview.bind(this),
			blur: this.fillReview.bind(this)
		});
	},
	fillReview : function(){
		if(this.one == $empty())
			this.startTime = new Date();
			
		diff = this.startTime.timeDiffInWords();
		text = this.textcontainer.get('value').stripTags().replace(/\n/g,'<br />').trim();
		if(this.one == $empty()){
			owner = (userstatus.fb && userstatus.fb.username) ? userstatus.fb.username : (userstatus.fb && userstatus.fb.first_name) ? ('{last_name} {first_name}').substitute(userstatus.fb) : userstatus.userData.user_email.split("@",1);
			
			this.one = new Element('div', {'class' : 'oneReview'}).setStyles({display: 'none'});
			new Element('div', {'class' : 'revTop'}).inject(this.one);
			var cont = new Element('div', {'class' : 'revContent'}).inject(this.one);
			new Element('span',{'class' : 'revOwner', 'html' : owner}).inject(cont);
			this.revcont = new Element('span', {'text' : text}).inject(cont);
			this.timecont = new Element('span',{'class' : 'revTime', 'text' : diff}).inject(cont, 'bottom');
			new Element('div', {'class' : 'revBottom'}).inject(this.one);
			this.one.inject(reviewsList, 'bottom');
			this.one.reveal();
			if(reviewsList.getChildren('div').length > 4){
				reviewsList.getChildren('div')[0].dissolve();
			}
		}
		else {
			this.timecont.set('text', diff);
			this.revcont.set('html', text);
		}
		this.wordCount.set('text',this.wordcount(text));
	},
	wordcount : function(string) {
		if(string.length == 0)
			return 0;		
	  var a = string.split(/\s+/g);
	  return a.length;
	}
});

var setReviewBtns = function(){
	$('sendReview').addEvent('submit', function(e){
		e.preventDefault();
		var text = reviewPreview.textcontainer.get('value').stripTags().trim().replace(/\t/g,'').replace(/\ {2,}/g,' ');
		reviewPreview.textcontainer.set('value', text);
		if(reviewPreview.wordcount(text) < 10)
			return false;
		new Request.JSON({url: api + 'addreview', method: 'post',
			onSuccess: function(json){
				if(json == 'OK'){
					reviewPreview.textcontainer.set('value', '');
					if(reviewPreview.one)
						reviewPreview.one = $empty();
					if(reviewsList.getChildren('div').length > 4){
						reviewsList.getChildren('div')[0].dispose();
					}
					if(revPagination.page != 1 || reviewsList.getChildren('div').length > 4){
						revPagination.page = 1;
						revPagination.loadContent();
					}
				}
			}
		}).send(this);

	});
	
	$('sendReview').addEvent('reset', function(e){
		e.preventDefault();
		if($('review').get('value').length == 0 && reviewPreview.one == $empty())
			return false;
		$('review').set('value', '');
		if(reviewPreview.one != $empty()){
			reviewPreview.one.nix(true);
			reviewPreview.one = $empty();
		}
		if(reviewsList.getChildren('div').length > 4)
			reviewsList.getChildren('div')[0].reveal();
	});
};

window.addEvent('domready', function(){
	ranks = new Rank();
	
	reviewsList = $('reviewsList');
	userstatus = new updateUserStatus({
		onLogin: function(){
			$('epReview').reveal();
			$('reviewBtn').setStyle('display','');
		},
		onLogout: function(){
			$('epReview').dissolve();
			$('reviewBtn').setStyle('display','none');
		}
	});
	if($$('.revRating .rankbar').length)
		ranks.add($$('.revRating .rankbar'),{countDisplay: $('rateDisplay')});
		
	reviewPreview = new makeReviewPreview;	
	revPagination = new buildRevPagination($('episodeid').get('value'),{container: $('reviewsList')});
	setReviewBtns();
	new ScScroller($('epOverview'));
});